﻿using Azure.Core;
using Novel.Server.Response;
using System.Drawing.Imaging;
using System.Drawing;

namespace Novel.Server.Utils
{
    public static class ImageUtils
    {
        /// <summary>
        /// 从输入获取图片
        /// </summary>
        public static async Task<byte[]> ReadImageFromRequest(HttpRequest request, int width, int height)
        {
            if (!request.ContentType?.StartsWith("image/") ?? true) return null;

            try
            {
                using var imageStream = new MemoryStream();
                await request.Body.CopyToAsync(imageStream);
                using var originalImage = System.Drawing.Image.FromStream(imageStream);

                int imageWidth = originalImage.Width;
                int imageHeight = originalImage.Height;
                double scale = Math.Max((double)width / imageWidth, (double)height / imageHeight);
                int newWidth = (int)Math.Round(imageWidth * scale);
                int newHeight = (int)Math.Round(imageHeight * scale);

                using var scaledImage = new Bitmap(originalImage, newWidth, newHeight);

                int cropX = (newWidth - width) / 2;
                int cropY = (newHeight - height) / 2;
                using var croppedImage = new Bitmap(width, height);
                using (Graphics g = Graphics.FromImage(croppedImage))
                {
                    g.DrawImage(scaledImage, new Rectangle(0, 0, width, height), new Rectangle(cropX, cropY, width, height), GraphicsUnit.Pixel);
                }

                using var outputStream = new MemoryStream();
                croppedImage.Save(outputStream, ImageFormat.Png);
                return outputStream.ToArray();
            }
            catch (Exception)
            {
                return null;
            }

        }
    }
}


